//
//  String+Extension.swift
//  Swift-Categary
//
//  Created by lantaiyuan on 2017/9/11.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

import Foundation
import UIKit

// 桥接文件导入头文件

let CC_LEN_FOR_TYPE = 4	// number of characters to determine length

extension String {
    
    var length : Int{
        get{
            return (self as NSString).length
        }
    }
    
    /// string 转 intvalue
    ///
    /// - Returns: int
    func int32Value() -> Int32 {
        return NSString(string : self).intValue
    }
    
    /// string 转 integer
    ///
    /// - Returns: Int
    func integerValue() -> Int {
        return NSString(string : self).integerValue
    }
    
    /// string 转 floatValue
    ///
    /// - Returns: float
    func floatValue() -> Float {
        return NSString(string : self).floatValue
    }
    
    /// String 转换 CGFloatValue
    ///
    /// - Returns: CGFloat
    func CGFloatValue() ->CGFloat{
        return CGFloat(self.floatValue())
    }
    
    /**
     String 转换 doubleValue
     
     - returns: double
     */
    func doubleValue() ->Double{
        return NSString(string: self).doubleValue
    }
    /**
     截取字符串
     
     - returns: String
     */
    func substringWithRange(_ range:NSRange) ->String {
        
        return NSString(string: self).substring(with: range)
    }
    
    /**
     获得文件的后缀名（不带'.'）
     
     - returns: String
     */
    func pathExtension() ->String {
        
        return NSString(string: self).pathExtension
    }
    
    /**
     从路径中获得完整的文件名（带后缀）
     
     - returns: String
     */
    func lastPathComponent() ->String {
        
        return NSString(string: self).lastPathComponent
    }
    
    /**
     获得文件名（不带后缀）
     
     - returns: String
     */
    func stringByDeletingPathExtension() ->String {
        
        return NSString(string: self).deletingPathExtension
    }
    
    /**
     字符串MD5加密
     - returns: MD5加密好的字符串
     */
    var MD5: String! {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        
        CC_MD5(str!, strLen, result)
        
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        
        result.deallocate(capacity: digestLen)
        
        return hash as String
    }

    /// 计算字符串大小
    func size(_ font:UIFont) ->CGSize {
        
        return size(font, constrainedToSize:CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    }
    
    /// 计算字符串大小
    func size(_ font:UIFont,constrainedToSize:CGSize) ->CGSize {
        
        let string:NSString = self as NSString
        
        return string.boundingRect(with: constrainedToSize, options: [.usesLineFragmentOrigin,.usesFontLeading], attributes: [NSFontAttributeName:font], context: nil).size
    }
    //邮箱验证
    static func justEmail(email:String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailPredicate.evaluate(with: email)
    }
    //手机号码验证
    static func justMobile(mobile:String) -> Bool {
        //手机号以13， 15，18开头，八个 \d 数字字符
        let phoneRegex = "^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phoneTest.evaluate(with:mobile)
    }
    
    //车牌号验证
    static func justCarNo(carNo:String) -> Bool {
        let carRegex = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
        let carPredicate = NSPredicate(format: "SELF MATCHES %@", carRegex)
        return carPredicate.evaluate(with: carNo)
    }
    //车型
    static func justCarType(CarType:String) -> Bool {
        let CarTypeRegex = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
        let carPredicate = NSPredicate(format: "SELF MATCHES %@", CarTypeRegex)
        return carPredicate.evaluate(with: CarType)
    }
    
    //用户名
    static func justUserName(name:String) -> Bool {
        
        let userNameRegex = "^[A-Za-z0-9]{6,20}+$"
        let userNamePredicate = NSPredicate(format: "SELF MATCHES %@", userNameRegex)
        let peopleName = userNamePredicate.evaluate(with: name)
        return peopleName
    }
    //密码
    static func justPassword(passWord:String) -> Bool {
        let passWordRegex = "^[a-zA-Z0-9]{6,20}+$"
        let passWordPredicate = NSPredicate(format:"SELF MATCHES %@",passWordRegex)
        return passWordPredicate.evaluate(with:passWord)
    }
    
    //昵称
    static func justNickname(nickname:String) -> Bool {
        let nicknameRegex = "^[a-zA-Z0-9]{6,20}+$"
        let passWordPredicate = NSPredicate(format:"SELF MATCHES %@",nicknameRegex)
        return passWordPredicate.evaluate(with:nickname)
    }
    
    
    //身份证号
    func justIdentityCard(identityCard:String) -> Bool {
        var flag = false
        if identityCard.characters.count <= 0 {
            flag = false
            return flag
        }
        let regex2 = "^(\\d{14}|\\d{17})(\\d|[xX])$"
        let identityCardPredicate = NSPredicate(format:"SELF MATCHES %@",regex2)
        return identityCardPredicate.evaluate(with:identityCard)
    }
    
    /**
     判断是不是数字
     */
    static func deptNumInputShouldNumber(str:String) -> Bool {
        let regex = "[0-9]*"
        let pred = NSPredicate(format:"SELF MATCHES %@",regex)
        if pred.evaluate(with: str) {
            return true
        } else {
            return false
        }
    }
    
    /****************************银行卡信息************************************************/
    // 银行卡号转正常号 － 去除4位间的空格
    static func bankNumToNormalNum(bankCardNumber:String) -> String {
        return bankCardNumber.replacingOccurrences(of: " ", with: "")
    }
    // 正常号转银行卡号 － 增加4位间的空格
    static func normalNumToBankNum(bankCardNumber:String) -> String {
        let size : Int = bankCardNumber.characters.count / 4
        let tmpStrArr = NSMutableArray.init()
        for n in 0..<size {
            let start = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: n*4)
            let end = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: 4)
            let myRange = start..<end
            
            tmpStrArr.add(bankCardNumber.substring(with: myRange))
        }
        let startIndex = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: size*4)
        let endIndex = bankCardNumber.index(bankCardNumber.startIndex, offsetBy: bankCardNumber.characters.count%4)
        let range = startIndex..<endIndex
        tmpStrArr.add(bankCardNumber.substring(with: range))
        
        let bankCard = tmpStrArr.componentsJoined(by: " ")
        
        return bankCard;
    }
    
    /**验证银行卡*/
    static func IsBankCard(cardNumber:String) -> Bool {
        if cardNumber.characters.count == 0 {
            return false
        }
        return true
    }
    
    //替换字符串
    public func cleanNumber(str:String) -> String {
        return str.replacingOccurrences(of: " ", with: "")
    }
    
    public func boundingRectWithStringFontWidth(string:String,font:UIFont,width:CGFloat) -> CGSize {
        
        let attr = NSMutableDictionary.init()
        attr[NSFontAttributeName] = font
        
        let statusLabelText: String = string
        
        let maxSize = CGSize(width:width, height:CGFloat(MAXFLOAT))
        
        let strSize = statusLabelText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
        return strSize
    }
    public func boundingRectWithStringFontHeight(string:String,font:UIFont,height:CGFloat) -> CGSize {
        
        let attr = NSMutableDictionary.init()
        attr[NSFontAttributeName] = font
        
        let statusLabelText: String = string
        
        let maxSize = CGSize(width:CGFloat(MAXFLOAT), height:height)
        
        let strSize = statusLabelText.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
        return strSize
    }
    public func boundingRectWithStringFont(string:String,font:UIFont) -> CGSize {
        
        let attr = NSMutableDictionary.init()
        attr[NSFontAttributeName] = font
        let maxSize = CGSize(width:CGFloat(MAXFLOAT), height:CGFloat(MAXFLOAT))
        let strSize = string.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
        return strSize
    }
    public func formatterCurrency(currency:String) -> String {
        let formatter = NumberFormatter.init()
        formatter.numberStyle = .decimal
        let remainingString = formatter.string(from: NSNumber.init(value: Int(currency)!))
        return (remainingString?.appending(".00"))!
    }
    
    public func formatterCurrencyWithCGflot(currency:CGFloat) -> String {
        let formatter = NumberFormatter.init()
        formatter.numberStyle = .decimal
        let remainingString = formatter.string(from: NSNumber.init(integerLiteral: Int(currency)))
        return remainingString!
    }
    
    /**
     第一个参数是传入一个CGSize结构体;
     第二个参数options是个配置选项
     高度计算时就传入NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
     如果你是用的String 的方法就有第三个参数：attributes其实就是NSAttributeString的属性，是个字典类型的对象，传入你的字体
     */
    
    public func WidthBoundingRectWithString(string:String,font:UIFont) ->CGSize {
        
        let statusLabelText: String = string
        
        let size = CGSize(width:CGFloat(MAXFLOAT), height:CGFloat(MAXFLOAT))
        
        let attr = NSMutableDictionary.init()
        attr[NSFontAttributeName] = font
        
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attr as? [String : AnyObject], context:nil).size
        
        return strSize
        
    }
    static func widthOfStringFontHeight(string:String,font:UIFont,height:CGFloat) -> CGFloat {
        
        let dict : NSDictionary = NSDictionary(object:font, forKey:NSFontAttributeName as NSCopying)
        let rect: CGRect = string.boundingRect(with:CGSize(width:CGFloat.greatestFiniteMagnitude,height:height) , options:.truncatesLastVisibleLine ,attributes:dict as? [String : Any],context: nil)
        return rect.size.width
    }
    static func heightOfStringFontWidth(string:String,font:UIFont,width:CGFloat) -> CGFloat {
        var bounds: CGRect
        let parameterDict: [NSObject : AnyObject] = NSDictionary(object: font, forKey: NSFontAttributeName as NSCopying) as [NSObject : AnyObject]
        bounds = string.boundingRect(with:CGSize(width:width,height:CGFloat.greatestFiniteMagnitude), options: .truncatesLastVisibleLine, attributes: parameterDict as? [String : Any],context: nil)
        return bounds.size.height
    }
    /*
     获取plist文件
     */
    static func resourcePathWithFileName(fileName:String,type:String) -> NSDictionary {
        
        let path = Bundle.main.path(forResource: fileName, ofType: type)
        let url = URL(fileURLWithPath:path!)
        var jsonDic:NSDictionary
        do {
            let data = try Data(contentsOf: url)
            let json:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            
            jsonDic = json as! NSDictionary
            return jsonDic
        } catch let error as Error!{
            print("读取本地数据出现错误！",error)
        }
        return NSDictionary()
    }
    
    /**
     ios通过图片的URL地址，从网络上获取图片(UIImage类型)
     @param fileURL 图片url
     @return uiimage
     */
    static func getImageFromURL(fileURL:String) -> UIImage {
        let result : UIImage
        let data = NSData.init(contentsOf: URL.init(string: fileURL)!)
        result = UIImage.init(data: data! as Data)!
        return result
    }
    /*
     获取ip地址
     */
    static func getIPAddress() -> String? {
        var address: String?
        // get list of all interfaces on the local machine
        var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
        
        guard getifaddrs(&ifaddr) == 0 else { return nil }
        guard let firstAddr = ifaddr else { return nil }
        
        // For each interface ...
        for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            
            let interface = ifptr.pointee
            
            // Check for IPV4 or IPV6 interface
            let addrFamily = interface.ifa_addr.pointee.sa_family
            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                // Check interface name
                let name = String(cString: interface.ifa_name)
                if name == "en0" {
                    // Convert interface address to a human readable string
                    var addr = interface.ifa_addr.pointee
                    var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    getnameinfo(&addr,
                                socklen_t(interface.ifa_addr.pointee.sa_len),
                                &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                    address = String(cString: hostName)
                }
            }
        }
        freeifaddrs(ifaddr)
        return address
    }
}

extension NSAttributedString{
    
    /// 计算多态字符串的size
    func size(_ constrainedToSize:CGSize?) ->CGSize{
        
        var tempConstrainedToSize = constrainedToSize
        
        if constrainedToSize == nil {tempConstrainedToSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)}
        
        return self.boundingRect(with: tempConstrainedToSize!, options: [NSStringDrawingOptions.usesLineFragmentOrigin,NSStringDrawingOptions.usesFontLeading], context: nil).size
    }
}













